package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;

import com.sky.mapper.OrderMapper;

import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;

import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;

import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper reportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceServiceImpl workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result turnoverStatistics(LocalDate begin, LocalDate end) {
        //先获取 begin 到 end 每一天的时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);

        }
        List turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            //2.1.获取当天的最小时间，年月日时分秒 00:00
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            //2.2 获取当天的最大时间，年月日时分秒 59:59
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", min);
            map.put("end", max);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportMapper.sumAmountByMap(map);
            //注意，此时返回的turnover，有可能为null,如果为null,我们则赋值为0
            if (turnover == null) {
                turnover = 0.0;
            }
            //2.6 把每一天的营业额添加到list中
            turnoverList.add(turnover);
        });
        TurnoverReportVO build = new TurnoverReportVO().builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();


        return Result.success(build);
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List totalUserList = new ArrayList();
        List newUserList = new ArrayList();
        dateList.forEach(date -> {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();

            map.put("end", max);
            //当日用户总数
            Integer totalUser = userMapper.countUserByMap(map);
            totalUserList.add(totalUser);
            //新增用户
            map.put("begin", min);
            Integer newUser = userMapper.countUserByMap(map);

            newUserList.add(newUser);

        });
        UserReportVO userReportVO = new UserReportVO().builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();

        return Result.success(userReportVO);
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //订单数列表，以逗号分隔
        List<Integer> orderCountList = new ArrayList<>();
        //有效订单数列表，以逗号分隔
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", min);
            map.put("end", max);
            //每日订单数
            orderCountList.add(reportMapper.countOrder(map));
            //每日有效订单数
            map.put("status", Orders.COMPLETED);//订单状态  已完成
            map.put("payStatus", Orders.PAID);//支付状态  已支付
            validOrderCountList.add(reportMapper.countOrder(map));
        });
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        OrderReportVO orderReportVO = new OrderReportVO().builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();

        return Result.success(orderReportVO);
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result top10(LocalDate begin, LocalDate end) {
        LocalDateTime newbegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime newend = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = reportMapper.top10(newbegin, newend);

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList, ","));

        return Result.success(salesTop10ReportVO);
    }

    /**
     * 营业数据导出
     *
     * @param response
     * @return
     */
    @Override
    public void export(HttpServletResponse response) {

        try {
            //获取前30天日期
            LocalDate begin = LocalDate.now().minusDays(30);//minusDays 减 plusDays 加
            LocalDate end = LocalDate.now().minusDays(1);
            //获取模板文件
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            //读取模板文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("日期：" + begin + "至" + end);
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            //数据概览
            //营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = end.minusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getNewUsers());

            }

            //通过输出流将文件下载到客户端浏览器中
            excel.write(response.getOutputStream());
            //关闭资源

            excel.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
